import globalVisionEntertainment.nba.Database;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

import javax.swing.*;

public class AverageFrame extends SheetFrame implements WindowListener, ActionListener
{

	JPopupMenu contextMenu;
	private final JButton showButton;
	private final JSpinner recentCountSpinner;
	private final String[] playerNames;
	private final int averageRange;

	public AverageFrame(String[] playerNames, int averageRange, int width)
	{
		super(true);

		this.playerNames = playerNames;
		this.averageRange = averageRange;

		setSize(new Dimension(width, 400));

		contextMenu = new JPopupMenu();
		addPopup(table, contextMenu);

		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());

		panel.add(new JScrollPane(table), BorderLayout.CENTER);

		JPanel panel2 = new JPanel();
		panel2.setLayout(new FlowLayout());

		showButton = new JButton("Show");
		showButton.addActionListener(this);
		panel2.add(showButton);
		panel2.add(new JLabel(" last"));
		recentCountSpinner = new JSpinner(new SpinnerNumberModel());

		recentCountSpinner.setPreferredSize(new Dimension(50, 30));
		recentCountSpinner.setValue(averageRange);
		panel2.add(recentCountSpinner);
		panel2.add(new JLabel("games"));

		panel.add(panel2, BorderLayout.SOUTH);

		getContentPane().add(panel);

		this.addWindowListener(this);

		// getContentPane().add(table);
	}

	@Override
	protected void loadData() throws IOException
	{
		Connection conn = null;
		try
		{
			conn = Database.getConnection();
			for (String playerName : playerNames)
			{
				// @formatter:off
				String sql =
						"SELECT `Player Name`,   "+
								"  SEC_TO_TIME(round(AVG(TIME_TO_SEC(`Total on Court`)))) as `Total On Court`,  "+
								"  SEC_TO_TIME(round(AVG(TIME_TO_SEC(`OnCourt1`)))) as `OnCourt1`,  "+
								"  SEC_TO_TIME(round(AVG(TIME_TO_SEC(`OnCourt2`)))) as `OnCourt2`,  "+
								"  SEC_TO_TIME(round(AVG(TIME_TO_SEC(`OnCourt3`)))) as `OnCourt3`,  "+
								"  SEC_TO_TIME(round(AVG(TIME_TO_SEC(`OnCourt4`)))) as `OnCourt4`,  "+
								"  round(avg(`Total Plus`)) as `Total Plus`,  "+
								"  round(avg(`1+`)) as `1+`,  "+
								"  round(avg(`2+`)) as `2+`,  "+
								"  round(avg(`3+`)) as `3+`,  "+
								"  round(avg(`4+`)) as `4+`,  "+
								"  round(avg(`Total Minus`)) as `Total Minus`,  "+
								"  round(avg(`1-`)) as `1-`,  "+
								"  round(avg(`2-`)) as `2-`,  "+
								"  round(avg(`3-`)) as `3-`,  "+
								"  round(avg(`4-`)) as `4-`,  "+
								"  (sum(`Total Plus`)+sum(`Total Minus`))/sum(TIME_TO_SEC(`Total on Court`))*60 as `Average`  "+
								"FROM     (select * from NBA.`player stat total`  "+
								"   where `Player Name`=\"%1s\"   "+
								"  order by  `Date` desc  limit 0,%2s) as T  ";
				// @formatter:on

				sql = String.format(sql, playerName, averageRange);

				Statement statement = conn.createStatement();
				statement.execute(sql);

				ResultSet resultSet = statement.getResultSet();
				ResultSetMetaData metaData = resultSet.getMetaData();

				int columnCount = metaData.getColumnCount();
				if (tableModel.getColumnCount() == 0)
				{
					tableModel.addColumn("");
					for (int i = 1; i <= columnCount; i++)
						tableModel.addColumn(metaData.getColumnLabel(i));
				}

				resultSet.first();

				do
				{
					Object[] rowData = new Object[columnCount + 1];
					rowData[0] = false;
					for (int i = 0; i < columnCount; i++)
					{
						rowData[i + 1] = resultSet.getString(i + 1);
					}
					tableModel.addRow(rowData);

				} while (resultSet.next());

			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (conn != null)
					conn.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
		}

	}

	private static void addPopup(Component component, final JPopupMenu popup)
	{
		component.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
					showMenu(e);
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
					showMenu(e);
			}

			private void showMenu(MouseEvent e)
			{
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}

	@Override
	public void windowOpened(WindowEvent e)
	{
		super.windowOpened(e);

		int characterLength = 70;
		String title = "Average of " + averageRange + " games for ";
		for (String playerName : playerNames)
		{
			title += playerName;
			if (title.length() > characterLength)
			{
				title += "...";
				break;
			}
			else
				title += ", ";
		}

		setTitle(title);

	}

	// @formatter:off
	@Override
	public void windowClosing(WindowEvent e)
	{
	}

	@Override
	public void windowClosed(WindowEvent e)
	{
	}

	@Override
	public void windowIconified(WindowEvent e)
	{
	}

	@Override
	public void windowDeiconified(WindowEvent e)
	{
	}

	@Override
	public void windowActivated(WindowEvent e)
	{
	}

	@Override
	public void windowDeactivated(WindowEvent e)
	{
	}

	// @formatter:on

	@Override
	public void actionPerformed(ActionEvent e)
	{
		assert e.getSource() == showButton;

		ArrayList<String> list = new ArrayList<String>();
		for (int i = 0; i < tableModel.getRowCount(); i++)
		{
			if (tableModel.getValueAt(i, 0).equals(true))
			{
				list.add((String) tableModel.getValueAt(i, 1));
				System.out.println(tableModel.getValueAt(i, 1));
			}
		}

		String[] playerNames = new String[list.size()];
		list.toArray(playerNames);

		DetailFrame f = new DetailFrame(playerNames, (int) recentCountSpinner.getValue(), getWidth());
		f.setVisible(true);

	}

}
